from flask import Blueprint,redirect,render_template,request,session
from utils import db
from . import input_info

ac = Blueprint('account', __name__)

# 登录接口
@ac.route('/login' ,methods = ['POST'])
def login():
    account = request.form.get('account')
    password = request.form.get('password')
    sql = 'select * from user where account = %s ;'
    result = db.get_one(sql,[account])
    if result is None:
        return render_template('login.html',msg='账号错误')
    else:
        if db.verify_password(password,result['password']) == False:
            return render_template('login.html',msg='密码错误')
        else:
            session['user_info'] = {'ID':result['ID'],'remark':result['remark'],'account':result['account'],'role':result['role']}
            return redirect('/user/list',code = 301)
    

# 注册接口
@ac.route('/sign' ,methods = ['POST'])
def sign():
    user = input_info.input_user_info()
    hash = db.hash_password(user['password'])
    password2 = request.form.get('password2')
    if db.verify_password(password2,hash) == False:
        return render_template('sign.html',msg='两次密码不一致')
    else:
        result =input_info.norm_user_info()
        if 'success' in result and result['success'] == True:
            sql = 'INSERT INTO user (remark,telephone1,telephone2,role,account, password) VALUES(%s, %s, %s, 1, %s, %s);'
            db.execute(sql,[user['remark'],user['telephone1'],user['telephone2'],user['account'],user['password']])
            return redirect('login.html',code = 302)
        else:
            return render_template('sign.html',msg=result['msg'])
    
